<?php
/**
 * author: crisen
 * email: crisen@crisen.org
 * date: 19-1-4
 * description:
 */

namespace App\Service;

use Illuminate\Support\Facades\Cache;


class Sms
{

    const SUFFIX_KEY = 'code';
    private static $name = '易物联盟';
    private static $appKey = '5E808182B5303D2C3E55DEB31EE2';
    private static $sign = '易物联盟';
    private static $url = 'http://web.duanxinwang.cc/asmx/smsservice.aspx';

    private static function getKey($phone)
    {
        return $phone . self::SUFFIX_KEY;
    }

    public static function getCode($phone)
    {
        $key = self::getKey($phone);
        $code = Cache::pull($key);
        return $code;
    }

    public static function generate($phone, $ttl = 1)
    {
        $code = mt_rand(1000, 9999);
        $key = self::getKey($phone);
        Cache::put($key, $code, $ttl);
        return $code;
    }

    public static function send($phone, $code)
    {
        $content = '您的短信验证码为' . $code . ',请勿将验证码提供给他人.';
        $params = self::parseParams($phone, $content);
        info("用户[$phone]的短信验证码是[$code]");
        //为了省钱 如果是本地环境 直接发送日志
        if (app()->environment('local')) {
            return true;
        }

        $res = self::curl(self::$url, $params, $post = true);
        if (!strpos($res, ',')) {
            return false;
        }
        $code = explode(',', $res)[0];
        if (0 == $code) {
            return true;
        }
        return false;
    }

    private static function parseParams($phone, $content)
    {
        return [
            'name' => self::$name,
            'pwd' => self::$appKey,
            'content' => $content,
            'mobile' => $phone,
            'sign' => self::$sign,
            'type' => 'pt'
        ];
    }


    protected static function curl($url, array $params = [], $isPost = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($isPost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            $params = http_build_query($params);
            curl_setopt($ch, CURLOPT_URL, $params ? "$url?$params" : $url);
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }


}